/**
 * 目录树
 * @example
<div class="coosTree">
	<script type="text/javascript">
		<!--
		//创建一个树对象
		tree = new coosTree('tree');
		//设置是否使用图标
		tree.config.useIcons = false;
		//tree.changeAll()打开或关闭所有节点,tree.o(id)为打开或关闭当前子节点
		//第一个参数为当前节点唯一id，第二个参数为父节点id，根节点的父节点id默认为-1,第三个参数为标题，第四个参数为url
		tree.add(0,-1,'全部非货币型基金','javascript:tree.changeAll();');
		tree.add(1,0,'基金品种','javascript:tree.o(1);');
			tree.add(2,1,'开放式','javascript:tree.o(2);');
				tree.add(3,2,'股票型','javascript:tree.o(3);');
					tree.add(4,3,'成长型','#this');
					tree.add(5,3,'价值型','#this');
					tree.add(6,3,'平衡型','#this');
					tree.add(7,3,'指数型','#this');
				tree.add(8,2,'配置型','javascript:tree.o(8);');
					tree.add(9,8,'保本型','#this');
					tree.add(10,8,'混合型','#this');
				tree.add(11,2,'债券型','#this');
			tree.add(12,1,'封闭式','javascript:tree.o(12);');
				tree.add(13,12,'股票型','javascript:tree.o(13);');
					tree.add(14,13,'成长型','#this');
					tree.add(15,13,'价值型','#this');
					tree.add(16,13,'平衡型','#this');
					tree.add(17,13,'指数型','#this');
			tree.add(18,1,'伞型基金','javascript:tree.o(18);');
				tree.add(19,18,'XX投资基金','#this');
			tree.add(20,1,'ETFs','#this');
			tree.add(21,1,'LOFs','#this');
			
		tree.add(22,0,'基金公司','javascript:tree.o(22);');
			tree.add(23,22,'基金公司名称','#this');
		
		document.write(tree);
		//-->
	</script>
</div>
 */
 
// Node object
function Node(id, pid, name, url, title, target, icon, iconOpen, open)
{
	this.id = id;
	this.pid = pid;
	this.name = name;
	this.url = url;
	this.title = title;
	this.target = target;
	this.icon = icon;
	this.iconOpen = iconOpen;
	this._io = open || false;
	this._is = false;
	this._ls = false;
	this._hc = false;
	this._ai = 0;
	this._p;
};

// Tree object
function coosTree(objName)
{
	this.config = {
		target			: null,
		folderLinks		: true,
		useSelection	: true,
		useCookies		: true,
		useLines		: true,
		useIcons		: true,
		useStatusText	: false,
		closeSameLevel	: false,
		inOrder			: false,
		oAllStatus      : false,
		imagePath		: "../images/coos/tree/"
	};

	this.icon = {
		root		: this.config.imagePath + 'base.gif',
		folder		: this.config.imagePath + 'folder.gif',
		folderOpen	: this.config.imagePath + 'folderopen.gif',
		node		: this.config.imagePath + 'page.gif',
		empty		: this.config.imagePath + 'empty.gif',
		line		: this.config.imagePath + 'line.gif',
		join		: this.config.imagePath + 'join.gif',
		joinBottom	: this.config.imagePath + 'joinbottom.gif',
		plus		: this.config.imagePath + 'plus.gif',
		plusBottom	: this.config.imagePath + 'plusbottom.gif',
		minus		: this.config.imagePath + 'minus.gif',
		minusBottom	: this.config.imagePath + 'minusbottom.gif',
		nlPlus		: this.config.imagePath + 'nolines_plus.gif',
		nlMinus		: this.config.imagePath + 'nolines_minus.gif'
	};

	this.obj = objName;

	this.aNodes = [];

	this.aIndent = [];

	this.root = new Node(-1);

	this.selectedNode = null;

	this.selectedFound = false;

	this.completed = false;
};

// Adds a new node to the node array
coosTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open)
{
	this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
};



// Open/close all nodes

coosTree.prototype.openAll = function()
{
	this.oAll(true);
};

coosTree.prototype.closeAll = function()
{
	this.oAll(false);
};

// Outputs the tree to the page
coosTree.prototype.toString = function()
{
	var str = '<div class="coosTree">\n';
	if (document.getElementById)
	{
		if (this.config.useCookies)
		{
			this.selectedNode = this.getSelected();
		}
		str += this.addNode(this.root);
	}
	else
	{
		str += 'Browser not supported.';
	}

	str += '</div>';

	if (!this.selectedFound){this.selectedNode = null;}

	this.completed = true;

	return str;

};

// Creates the tree structure
coosTree.prototype.addNode = function(pNode)
{
	var str = '';
	var n=0;
	if (this.config.inOrder) n = pNode._ai;

	for (n; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n].pid == pNode.id)
		{
			var cn = this.aNodes[n];
			cn._p = pNode;
			cn._ai = n;
			this.setCS(cn);

			if (!cn.target && this.config.target){cn.target = this.config.target;}

			if (cn._hc && !cn._io && this.config.useCookies){cn._io = this.isOpen(cn.id);}

			if (!this.config.folderLinks && cn._hc){cn.url = null;}

			if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound)
			{
					cn._is = true;
					this.selectedNode = n;
					this.selectedFound = true;
			}
			str += this.node(cn, n);
			if (cn._ls) break;
		}
	}
	return str;
};

// Creates the node icon, url and text
coosTree.prototype.node = function(node, nodeId)
{
	var str = '<div class="coosTreeNode">' + this.indent(node, nodeId);
	if (this.config.useIcons)
	{
		if (!node.icon)
		{
			node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
		}
		if (!node.iconOpen)
		{
			node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
		}
		if (this.root.id == node.pid)
		{
			node.icon = this.icon.root;
			node.iconOpen = this.icon.root;
		}
		str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
	}

	if (node.url)
	{
		str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"';
		if (node.title){str += ' title="' + node.title + '"';}

		if (node.target){str += ' target="' + node.target + '"';}

		if (this.config.useStatusText){str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';}

		if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))
		{
			str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';
		}
		str += '>';
	}
	else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)
	{
		str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';
	}
	str += node.name;

	if (node.url || ((!this.config.folderLinks || !node.url) && node._hc))
	{
		str += '</a>';
	}
	str += '</div>';

	if (node._hc)
	{
		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
		str += this.addNode(node);
		str += '</div>';
	}

	this.aIndent.pop();
	return str;
};

// Adds the empty and line icons
coosTree.prototype.indent = function(node, nodeId)
{
	var str = '';
	if (this.root.id != node.pid)
	{
		for (var n=0; n<this.aIndent.length; n++)
		{
			str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
		}
		(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);

		if (node._hc)
		{
			str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
			if (!this.config.useLines)
			{
				str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
			}
			else
			{
				str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
			}
			str += '" alt="" /></a>';

		} 
		else 
		{
			str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
		}
	}
	return str;
};

// Checks if a node has any children and if it is the last sibling
coosTree.prototype.setCS = function(node)
{
	var lastId;
	for (var n=0; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n].pid == node.id){node._hc = true;}
		if (this.aNodes[n].pid == node.pid){lastId = this.aNodes[n].id;}
	}
	if (lastId==node.id) node._ls = true;
};

// Returns the selected node
coosTree.prototype.getSelected = function()
{
	var sn = this.getCookie('cs' + this.obj);
	return (sn) ? sn : null;
};

// Highlights the selected node
coosTree.prototype.s = function(id)
{
	if (!this.config.useSelection) return;
	var cn = this.aNodes[id];
	if (cn._hc && !this.config.folderLinks) return;
	if (this.selectedNode != id)
	{
		if (this.selectedNode || this.selectedNode==0)
		{
			eOld = document.getElementById("s" + this.obj + this.selectedNode);
			eOld.className = "node";
		}
		eNew = document.getElementById("s" + this.obj + id);
		eNew.className = "nodeSel";
		this.selectedNode = id;
		if(this.config.useCookies)
		{
			this.setCookie('cs' + this.obj, cn.id);
		}
	}
};



// Toggle Open or close
coosTree.prototype.o = function(id)
{
	var cn = this.aNodes[id];
	this.nodeStatus(!cn._io, id, cn._ls);
	cn._io = !cn._io;
	if(this.config.closeSameLevel)
	{
		this.closeLevel(cn);
	}
	if(this.config.useCookies)
	{
		this.updateCookie();
	}
};

// Open or close all nodes
coosTree.prototype.oAll = function(status)
{
	this.config.oAllStatus = status;
	for (var n=0; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id)
		{
			this.nodeStatus(status, n, this.aNodes[n]._ls)
			this.aNodes[n]._io = status;
		}
	}
	if (this.config.useCookies) this.updateCookie();
};

// Open all close nodes OR close all open nodes
coosTree.prototype.changeAll = function()
{
	if(this.config.oAllStatus)
	{
		this.closeAll();
	}
	else
	{
		this.openAll();
	}
};

// Opens the tree to a specific node

coosTree.prototype.openTo = function(nId, bSelect, bFirst)
{
	if (!bFirst)
	{
		for (var n=0; n<this.aNodes.length; n++)
		{
			if (this.aNodes[n].id == nId)
			{
				nId=n;
				break;
			}
		}
	}
	var cn=this.aNodes[nId];
	if (cn.pid==this.root.id || !cn._p) return;
	cn._io = true;
	cn._is = bSelect;
	if (this.completed && cn._hc){this.nodeStatus(true, cn._ai, cn._ls);}

	if (this.completed && bSelect)
	{
		this.s(cn._ai);
	}
	else if (bSelect)
	{
		this._sn=cn._ai;
	}
	this.openTo(cn._p._ai, false, true);
};

// Closes all nodes on the same level as certain node
coosTree.prototype.closeLevel = function(node)
{
	for (var n=0; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc)
		{
			this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
}

// Closes all children of a node
coosTree.prototype.closeAllChildren = function(node)
{
	for (var n=0; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc)
		{
			if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
}

// Change the status of a node(open or closed)
coosTree.prototype.nodeStatus = function(status, id, bottom)
{
	eDiv = document.getElementById('d' + this.obj + id);
	eJoin = document.getElementById('j' + this.obj + id);
	if (this.config.useIcons)
	{
		eIcon = document.getElementById('i' + this.obj + id);
		eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
	}
	eJoin.src = (this.config.useLines)?

	((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):

	((status)?this.icon.nlMinus:this.icon.nlPlus);

	eDiv.style.display = (status) ? 'block': 'none';
	
	var re = "d" + this.obj;
	var oReg = new RegExp(re, "g");
	//如果父节点为隐藏则同时打开
	if(eDiv.parentNode.style.display == "none" && oReg.test(eDiv.parentNode.id))
	{
		this.o(eDiv.parentNode.id.replace(oReg,""));
	}
	

};

// [Cookie] Clears a cookie
coosTree.prototype.clearCookie = function()
{
	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
	this.setCookie('co'+this.obj, 'cookieValue', yesterday);
	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};

// [Cookie] Sets value in a cookie
coosTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure)
{
	document.cookie = escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};

// [Cookie] Gets a value from a cookie
coosTree.prototype.getCookie = function(cookieName)
{
	var cookieValue = '';
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if (posName != -1)
	{
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = document.cookie.indexOf(';', posValue);
		if (endPos != -1)
		{
			cookieValue = unescape(document.cookie.substring(posValue, endPos));
		}
		else
		{
			cookieValue = unescape(document.cookie.substring(posValue));
		}
	}
	return (cookieValue);
};

// [Cookie] Returns ids of open nodes as a string
coosTree.prototype.updateCookie = function()
{
	var str = '';
	for (var n=0; n<this.aNodes.length; n++)
	{
		if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id)
		{
			if (str) str += '.';
			str += this.aNodes[n].id;
		}
	}
	this.setCookie('co' + this.obj, str);
};

// [Cookie] Checks if a node id is in a cookie
coosTree.prototype.isOpen = function(id)
{
	var aOpen = this.getCookie('co' + this.obj).split('.');
	for (var n=0; n<aOpen.length; n++)
	{
		if (aOpen[n] == id){return true;}
	}
	return false;
};

// If Push and pop is not implemented by the browser
if (!Array.prototype.push)
{
	Array.prototype.push = function array_push()
	{
		for(var i=0;i<arguments.length;i++)
		{
			this[this.length]=arguments[i];
		}
		return this.length;
	};
};

if (!Array.prototype.pop)
{
	Array.prototype.pop = function array_pop()
	{
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	};
};